<?php

namespace App\Http\Controllers\Admin;

use App\Models\BookHomeBudgetLog;
use App\Models\BookHomePostageSet;
use App\Models\BookHomePurchaseSet;
use App\Models\BookHomeReturnAddress;
use App\Models\Manage;
use App\Models\Shop;
use App\Validate\BookHomePurchaseSetValidate;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 图书到家系统设置
 * Class SystemSet
 * @package app\api\controller
 */
class BookHomePurchaseSetController extends CommonController
{
    private $validate = null;
    private $model = null;
    public function __construct()
    {
        parent::__construct();
        $this->model = new BookHomePurchaseSet();
        $this->validate = new BookHomePurchaseSetValidate();
    }

    /**
     * 图书经费+读者采购设置
     * @param type  类型
     * 1 图书采购经费预算
     * 2.逾期滞纳金（多少元每天）
     * 3.每人每次可采购图书本数
     * 4.每人每次可采购图书金额
     * 5.每人每月可采购图书本数
     * 6.每人每月可采购图书金额
     * 7.每人每年可采购图书本数
     * 8.每人每年可采购图书金额
     * 9.单本金额上限
     * 10.复本数不允许超过 几本（图书馆系统）
     * 11.多少年之前的书不允许采购（0 表示全部都可以采购）
     * 12.读者一次性借阅的天数
     * 13.书籍损坏赔偿原价的 多少（百分比） 只需要数字部分
     * 14.图书采购邮费预算
   //  * 15.积分扣除比例  （欠费缴纳）   在欠费设置里面配置，不在这里设置
     * 16.复本数不允许超过 几本（本系统）
     * 17.每人同种书不允许超过 几本（增对新书有效）0或空 表示只能采购一本
     * 18.有效复本书计算排除的馆藏地点代码（多个逗号拼接） 空表示所有馆藏都计算
     * 19.馆藏书可借阅（可检索）的馆藏地点代码（多个逗号拼接） 空表示都可以借阅
     *
     * @param number 数量（金额） 如果 type为 1 或 14  就是本次增加或减少金额     18，19 为文本
     * @param node   如果 type为1 或 14 必选   其余不需要此参数   增加还是减少金额   1增加   2减少
     * @param start_time   如果 type为14  必选 其余无效  开始时间
     * @param end_time   如果 type为14  必选 其余无效   结束时间
     * @param times   如果 type为14  必选 其余无效   次数
     * @param way   如果 type为14 必选   其余不需要此参数   1 独立模式（只生效一次）  2 循环模式
     * @param month_number   如果 type为14 必选   其余不需要此参数  循环月的数量 几个月循环一次（默认1）范围 1~12
     * @param start_month   如果 type为14 必选   其余不需要此参数  开始月份（开始的月份）
     */
    public function purchaseSet()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('purchase_set')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        if ($this->request->type == 15) {
            return $this->returnApi(201, '参数错误'); //15.积分扣除比例  （欠费缴纳）   在欠费设置里面配置，不在这里设置
        }

        if (($this->request->type == 1 || $this->request->type == 14) && empty($this->request->node)) {
            return $this->returnApi(201, '参数错误');
        }
        /*  if ($this->request->type == 14 && (empty($this->request->start_time) || empty($this->request->end_time) || empty($this->request->times))) {
          return $this->returnApi(201, '参数错误');
      }*/
        if (empty($this->request->number) && $this->request->type != 14 && $this->request->type != 11 && $this->request->type != 18 && $this->request->type != 19) {
            return $this->returnApi(201, '参数错误');
        }

        if (!is_numeric($this->request->number) && ($this->request->type != 18 && $this->request->type != 19)) {
            return $this->returnApi(201, '数量或金额必须为数字');
        }


        if ($this->request->type == 14 && !empty($this->request->times)) {
            if (empty($this->request->way)) {
                return $this->returnApi(201, '模式不能为空');
            }
            if (empty($this->request->start_time) || empty($this->request->end_time)) {
                return $this->returnApi(201, '时间不能为空');
            }
            if ($this->request->way == 1) {
                if (!is_date($this->request->start_time) || !is_date($this->request->end_time)) {
                    return $this->returnApi(201, '开始时间或结束时间格式不正确');
                }
            } else {
                if (!is_numeric($this->request->start_time) || !is_numeric($this->request->end_time)) {
                    return $this->returnApi(201, '开始号数或结束号数格式不正确');
                }
                if ($this->request->start_time > $this->request->end_time) {
                    return $this->returnApi(201, '开始号数不能大于结束号数');
                }
                if (empty($this->request->month_number)) {
                    return $this->returnApi(201, '循环月的数量不能为空');
                }
                if (empty($this->request->start_month)) {
                    return $this->returnApi(201, '开始月份不能为空');
                }
                if (empty(date('Y-m-d', strtotime($this->request->start_month)))) {
                    return $this->returnApi(201, '开始月份格式不正确');
                }
            }
        }

        $res = $this->model->where('type', $this->request->type)->first();

        DB::beginTransaction();

        $number = $this->request->number;
        $total = $res['number'];
        try {
            if ($res) {
                if ($this->request->type == 1 || $this->request->type == 14) {
                    $number = $this->model->countTotalMoney($total, $this->request->node, $this->request->number);
                }
                if ($this->request->type == 14) {
                    $res->start_time = $this->request->way == 1 ? $this->request->start_time : ($this->request->month_number == 1 ? $this->request->start_time : 1);
                    $res->end_time =  $this->request->way == 1 ? $this->request->end_time : ($this->request->month_number == 1 ? $this->request->end_time : 31);
                    $res->times =  !empty($this->request->times) ? $this->request->times : null;
                    $res->month_number =  $this->request->way == 2 ? $this->request->month_number : null;
                    $res->start_month =  $this->request->way == 2 ? date('Y-m', strtotime($this->request->start_month)) : null;
                }

                if ($this->request->type == 18 || $this->request->type == 19) {
                    $res->content = $number; //内容存放在content
                } else {
                    $res->number = $number;
                }

                $res->way =  $this->request->input('way', null);
                $res->save();
            } else {
                if ($this->request->type == 18 || $this->request->type == 19) {
                    $this->model->content =  $number;
                } else {
                    $this->model->number = $number;
                }

                $this->model->way =  $this->request->input('way', null);

                $this->model->type = $this->request->type;
                $this->model->number = $number;
                $this->model->save();
            }
            //需要添加历史记录
            if ($this->request->type == 1 || $this->request->type == 14) {
                $kind = $this->request->type == 1 ? 1 : 2; //种类   1 经费   2 邮费
                //更改之前剩余金额
                $change_before_money = $this->model->countBeforeSurplusMoney($total, $kind);
                //更改之后剩余金额
                $change_after_money = $this->model->countAfterSurplusMoney($total, $this->request->node, $this->request->number, $kind);

                $bookHomeBudgetLogModel = new BookHomeBudgetLog();
                if ($this->request->type == 14) {
                    $data = [
                        'type' => $this->request->node,
                        'kind' => $kind,
                        'money' => $this->request->number, //原本数量
                        'total_money' => $total,
                        'after_total_money' => $number, //最后数量
                        'change_before_money' => $change_before_money,
                        'change_after_money' => $change_after_money,
                        'start_time' => $this->request->way == 1 ? $this->request->start_time : ($this->request->month_number == 1 ? $this->request->start_time : 1),
                        'end_time' => $this->request->way == 1 ? $this->request->end_time : ($this->request->month_number == 1 ? $this->request->end_time : 31) ,
                        'times' => $this->request->times,
                        'way' => $this->request->way,
                        'month_number' =>  $this->request->way == 2 ? $this->request->month_number : null,
                        'start_month' =>  $this->request->way == 2 ? date('Y-m', strtotime($this->request->start_month)) : null,
                        'manage_id' => request()->manage_id,
                    ];

                } else {
                    $data = [
                        'type' => $this->request->node,
                        'kind' => $kind,
                        'money' => $this->request->number,
                        'total_money' => $total,
                        'after_total_money' => $number,
                        'change_before_money' => $change_before_money,
                        'change_after_money' => $change_after_money,
                        'manage_id' => request()->manage_id,
                    ];
                }

                $bookHomeBudgetLogModel->add($data);
            }
            DB::commit();
            return $this->returnApi(200, '设置成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
    /**
     * 邮费设置 或修改
     * @param content json格式    [{"number":1,"price":1},{"number":2,"price":2},{"number":3,"price":3}]  删除所有  content为 字符串
     * @param number  本数   书的本数必须连续
     * @param type  类型  1 新书  2 馆藏书
     * @param price 金额
     */
    public function postageSet()
    {
        /* $content = [
            ['number'=>1 , 'price'=>1 , 'type'=>1],
            ['number'=>2 , 'price'=>2, 'type'=>1],
            ['number'=>3 , 'price'=>3, 'type'=>1],
        ];*/

        //增加验证场景进行验证
        if (!$this->validate->scene('postage_set')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }


        $content = json_decode($this->request->content, true);

        $content = sort_arr_by_one_field($content, 'number', [SORT_NUMERIC, SORT_ASC]); //本书按照从小到大排序
        $bookHomePostageSetModel = new BookHomePostageSet();

        if (isset($content[0]['type'])) {
            $type = $content[0]['type'];
        } else {
            return $this->returnApi(201, '网络错误，请刷新后重试');
        }
        DB::beginTransaction();
        try {
            $bookHomePostageSetModel->where('type', $type)->delete();
            if (!empty($content)) {
                $i = 1;
                foreach ($content as $key => $val) {
                    if (empty($val) || empty($val['number']) || empty($val['price']) || !is_numeric($val['number'])) {
                        throw new \Exception('设置失败');
                    }
                    //金额不允许小于 1分
                    if ($val['price'] < 0.01) {
                        throw new \Exception('邮费设置失败');
                    }
                    //判断是否是连续数字
                    if ($val['number'] != $i) {
                        throw new \Exception('书的本数必须连续');
                    }
                    $content[$key]['create_time'] = date('Y-m-d H:i:s');
                    $content[$key]['change_time'] = date('Y-m-d H:i:s');

                    $i++;
                }
                $bookHomePostageSetModel->insert($content);
            }
            DB::commit();
            return $this->returnApi(200, '设置成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 设置记录数据
     */
    public function purchaseSetRecord()
    {
        $res = $this->model->orderByDesc('type')->get();
        $result = [];
        foreach ($res as $key => $val) {
            $result[$val['type']]['content'] = $val['content'];
            $result[$val['type']]['number'] = $val['number'];
            $result[$val['type']]['start_time'] = $val['start_time'];
            $result[$val['type']]['end_time'] = $val['end_time'];
            $result[$val['type']]['times'] = $val['times'];
            $result[$val['type']]['way'] = $val['way'];
            $result[$val['type']]['month_number'] = $val['month_number'];
            $result[$val['type']]['start_month'] = $val['start_month'];
        }
        $name = $this->setName();
        $data = [];
        $bookHomePostageSetModel = new BookHomePostageSet();
        for ($i = 1; $i < 20; $i++) {
            if ($i == 15) {
                continue; //去掉15的数据获取
            }
            if ($i == 1 || $i == 14) {
                $data[$name[$i]]['start_time'] = !empty($result[$i]['start_time']) ? $result[$i]['start_time'] : null;
                $data[$name[$i]]['end_time'] = !empty($result[$i]['end_time']) ? $result[$i]['end_time'] : null;
                $data[$name[$i]]['times'] = !empty($result[$i]['times']) ? $result[$i]['times'] : 0;
                $data[$name[$i]]['way'] = !empty($result[$i]['way']) ? $result[$i]['way'] : 1;

                $data[$name[$i]]['month_number'] = !empty($result[$i]['month_number']) ? $result[$i]['month_number'] : 1;
                $data[$name[$i]]['start_month'] = !empty($result[$i]['start_month']) ? $result[$i]['start_month'] : null;

                $data[$name[$i]]['total'] = !empty($result[$i]['number']) ? sprintf("%.2f", $result[$i]['number']) : "0.00";

                $data[$name[$i]]['have_been_used'] = $i == 1 ? $this->model->getBookHomePurchaseMoney() : $this->model->getPostageMoney();
                $data[$name[$i]]['surplus'] = sprintf("%.2f", $data[$name[$i]]['total'] - $data[$name[$i]]['have_been_used']); //剩余金额
            } elseif ($i == 18 || $i == 19) {
                $data[$name[$i]] = !empty($result[$i]['content']) ? (string)$result[$i]['content'] : "";
            } else {
                $data[$name[$i]] = !empty($result[$i]['number']) ? (string)$result[$i]['number'] : "0";
            }
        }
        //获取设置的邮费列表
        $data['shop_postage'] = $bookHomePostageSetModel->select('number', 'price')->where('type', 1)->get();
        $data['lib_postage'] = $bookHomePostageSetModel->select('number', 'price')->where('type', 2)->get();
        $bookHomeReturnAddressModel = new BookHomeReturnAddress();
        $data['lib_postal_address_info'] = $bookHomeReturnAddressModel->getDeliverAddress(2); //图书馆发货地址
        $shop_list = Shop::select('id', 'name')->where('way', '<>', 2)->where('is_del', 1)->get();
        foreach ($shop_list as $key => $val) {
            $shop_list[$key]['address_info'] = $bookHomeReturnAddressModel->getDeliverAddress(1, $val['id']); //书店发货地址
        }
        $data['shop_postal_address_info'] = $shop_list; //书店地址信息

        return $this->returnApi(200, '获取成功', true, $data);
    }


    /**
     * 采购预算、邮费 增加的历史表
     * @param kind 种类   1 经费（默认）   2 邮费
     * @param page int 页码
     * @param limit int 分页大小
     */
    public function purchaseBudgetList()
    {
        $page = intval($this->request->page, 1) ?: 1;
        $limit = intval($this->request->limit, 10) ?: 10;
        $kind = $this->request->input('kind', 1);

        $bookHomeBudgetLog = new BookHomeBudgetLog();
        $res =  $bookHomeBudgetLog->lists(null, $kind, $limit);
        if ($res['data']) {
            $res['data'] = $this->disDataSameLevel($res['data'], 'con_manage', [Manage::$manage_name => 'manage_name']);
            $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);

            $res = $this->disPageData($res);

            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 图书馆发货地址设置
     * @param username  发货人名称
     * @param tel  发货人联系电话号码
     * @param province 省
     * @param city 市
     * @param district 区
     * @param street 街道
     * @param address 详细地址
     */
    public function libDeliverAddress()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('lib_deliver_address')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $bookHomeReturnAddressModel = new BookHomeReturnAddress();
        $data = $this->request->all();
        $data['type'] = 2;


        list($res, $msg) = $bookHomeReturnAddressModel->setDeliverAddress($data);

        if ($res) {
            return $this->returnApi(200, $msg . '成功', true);
        }
        return $this->returnApi(202, $msg . '失败');
    }

    /**
     * 书店发货地址设置
     * @param shop_id  书店id
     * @param username  发货人名称
     * @param tel  发货人联系电话号码
     * @param province 省
     * @param city 市
     * @param district 区
     * @param street 街道
     * @param address 详细地址
     */
    public function shopDeliverAddress()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('shop_deliver_address')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $bookHomeReturnAddressModel = new BookHomeReturnAddress();
        $data = $this->request->all();
        $data['type'] = 1;
        list($res, $msg) = $bookHomeReturnAddressModel->setDeliverAddress($data);
        if ($res) {
            return $this->returnApi(200, $msg . '成功', true);
        }
        return $this->returnApi(202, $msg . '失败');
    }


    /**
     * 设置荐购参数名称
     * 1 图书采购预算（总预算）
     * 2.逾期滞纳金（多少元每天）
     * 3.每人每次可采购图书本数
     * 4.每人每次可采购图书金额
     * 5.每人每月可采购图书本数
     * 6.每人每月可采购图书金额
     * 7.每人每年可采购图书本数
     * 8.每人每年可采购图书金额
     * 9.单本金额上限
     * 10. 复本数不允许超过 几本
     * 11.多少年之前的书不允许采购（0 表示全部 都可以采购）
     * 12.读者一次性借阅的天数
     * 13.书籍损坏赔偿原价的 多少（百分比）
     * 14.图书采购邮费预算（总预算）
     * 15.积分扣除比例  （欠费缴纳）
     * 16.复本数不允许超过 几本（本系统）
     * 17.每人同种书不允许超过 几本（增对新书有效）
     * 18.有效复本书计算排除的馆藏地点代码（多个逗号拼接）
     * 19.馆藏书可借阅的馆藏地点代码（多个逗号拼接）
     */
    public function setName()
    {
        return [
            '1' => 'purchase_budget',
            'late_fee',
            'person_time_number',
            'person_time_money',
            'person_month_number',
            'person_month_money',
            'person_year_number',
            'person_year_money',
            'one_money',
            'duplicate_number',
            'not_allow_year',
            'borrow_day',
            'damage',
            'postage_budget',
            'subscription_ratio',
            'this_system_duplicate_number',
            'every_people_number',
            'duplicate_exclude_collection_point',
            'search_collection_point',
        ];
    }
}
